import * as T from '../types';
import {store2Props} from '../selectors';
import actions from '../actions/index';
import {View, Text, Image} from '@tarojs/components';
import {connect} from 'react-redux';
import Taro from '@tarojs/taro';
import React, {Component} from 'react';
import moment from 'dayjs';
var isSameOrBefore = require('dayjs/plugin/isSameOrBefore');
moment.extend(isSameOrBefore);
import {_, WMkit, immutable} from 'wmkit';
import {debounce} from 'lodash';
// import '../css/style.less';
import CountDown from '@/pages/common/count-down';
import PriceAll from '@/pages/common/goods/priceAll';
import noneImg from '@/assets/image/default/no-goods-img.png';
type IOrderListProps = T.IProps & T.IOrderListProps;
import dowmImg from '@/assets/image/coupon/down.png';
import './order-list-item.less';
import Price from '@/pages/common/goods/price';
import {Label} from '@wanmi/ui-taro';
/**
 * 订单状态
 * @type {{INIT: string; GROUPON: string; AUDIT: string; DELIVERED_PART: string; DELIVERED: string; CONFIRMED: string; COMPLETED: string; VOID: string}}
 */
const flowState = (status, payState, paymentOrder) => {
  if (status == 'INIT') {
    return '待审核';
  } else if (status == 'GROUPON') {
    // 是拼团订单 根据支付状态 ? 待支付 : 待发货
    if (payState == 'NOT_PAID') {
      return '待付款';
    } else if (payState == 'UNCONFIRMED') {
      return '待确认';
    } else if (payState == 'PAID') {
      return '待发货';
    }
  } else if (status == 'AUDIT' && payState == 'NOT_PAID' && paymentOrder == 'PAY_FIRST') {
    return '待付款';
  } else if (status == 'AUDIT' && payState == 'UNCONFIRMED' && paymentOrder == 'PAY_FIRST') {
    return '待付款';
  } else if (status == 'WAIT_PAY_EARNEST' && payState == 'NOT_PAID') {
    return '待支付定金';
  } else if (
    (status == 'WAIT_PAY_TAIL' && payState == 'PAID_EARNEST') ||
    (status == 'AUDIT' && payState == 'PAID_EARNEST')
  ) {
    return '待支付尾款';
  } else if (status == 'CONFIRMED') {
    return '已收货';
  } else if (status == 'AUDIT' || status == 'DELIVERED_PART') {
    return '待发货';
  } else if (status == 'DELIVERED') {
    return '待收货';
  } else if (status == 'COMPLETED') {
    return '已完成';
  } else if (status == 'VOID') {
    return '已作废';
  }
};

@connect<Partial<IOrderListProps>, T.IOrderListState>(store2Props, actions)
export default class OrderList extends Component<Partial<IOrderListProps>, T.IOrderListState> {
  constructor(props: IOrderListProps) {
    super(props);

    this.state = {
      maxNum: 5,
    };
  }

  render() {
    let {main, order, index, inviteeShopName} = this.props;
    const {maxNum} = this.state;
    const opeBtnArr = this.getOpeBtnArr(immutable.fromJS(main.orders[index]));
    const gifts = (order && order.gifts) || [];
    const endTime =
      order && order.orderTimeOut && !moment(order.orderTimeOut).isBefore(main.serverTime)
        ? moment(order.orderTimeOut)
        : null;
    //商品清单展示形式  0:普通 1: 明细
    order.type = main.orderListType;

    return (
      <View>
        <View className="user-box" key={order.id}>
          <View
            className="user-order-item"
            onClick={() => {
              Taro.navigateTo({url: `/pages/package-C/order/order-detail/index?id=${order.id}`});
            }}
          >
            <View className="user-order-item-link">
              {WMkit.inviteeId() && WMkit.isShop() ? (
                <View
                  style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  <View className="dinapu">
                    <Text className="name">
                      {order.storeBagsFlag == 1 ? inviteeShopName : `${order.distributorName}的${order.shopName}`}
                    </Text>
                  </View>
                  <Image className="icon" src={require('../img/jiantou.png')} />
                </View>
              ) : (
                <View
                  style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  {!(order && order.platform == 'CUSTOMER') && (
                    <Image className="icon" src={require('../img/dai.png')} />
                  )}

                  {order.supplier.isSelf == true ? <Label name="自营" type="gold" /> : null}
                  <View className="dian-pu">
                    <Text className="store-title">{order.supplier.storeName}</Text>
                  </View>
                  <Image className="icon" src={require('../img/jiantou.png')} />
                </View>
              )}

              {order && (
                <View
                  className={
                    order.tradeState.flowState == 'COMPLETED' ||
                    order.tradeState.flowState == 'CONFIRMED' ||
                    order.tradeState.flowState == 'VOID'
                      ? 'order-list-item-status'
                      : 'order-list-item-status2'
                  }
                >
                  {flowState(order.tradeState.flowState, order.tradeState.payState, order.paymentOrder)}
                </View>
              )}
            </View>

            {order.type == 0 ? (
              <View className="middle">
                {order
                  ? order.tradeItems
                      .concat(gifts)
                      .filter((val, index) => index < 4)
                      .map((item, index) => (
                        <View className="pic">
                          <Image className="img-item" key={index} src={item.pic ? item.pic : noneImg} />
                          <View className="name">{item.skuName}</View>
                        </View>
                      ))
                    : null}
                <View className="right">
                  {order ? order.tradeItems.concat(gifts).length : null}
                  <Image className="icon" src={require('../img/jiantou.png')} />
                </View>
              </View>
            ) : (
              <View className="middle-detail">
                {order
                  ? order.tradeItems
                      .concat(gifts)
                      .filter((val, index) => index < maxNum)
                      .map((item, index) => (
                        <View className="product-item" key={index}>
                          <Image className="img-item" src={item.pic ? item.pic : noneImg} />
                          <View className="content">
                            <View className="content-detail">
                              <View className="name">{item.skuName}</View>
                              <View className="specDetails">{item.specDetails ? item.specDetails : ''}</View>
                            </View>
                            <View className="content-right">
                              <View className="price">
                                {/* <Text className="unit">
                                  ￥<Text className="fixed1">{toFixed2(item.price || 0).split('.')[0]}</Text>.
                                  {toFixed2(item.price || 0).split('.')[1]}
                                </Text> */}
                                <Price price={_.addZero(item.price)} buyPoint={item.buyPoint} />
                              </View>
                              <View className="number">{'x' + item.num}</View>
                            </View>
                          </View>
                        </View>
                      ))
                  : null}
              </View>
            )}

            {order.type == 1 && order.tradeItems.length > maxNum && (
              <View
                className="product-more"
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({maxNum: order.tradeItems.length});
                }}
              >
                剩余{order.tradeItems.length - maxNum}种商品
                <Image className="down-img" src={require('../img/jiantoudown.png')} />
              </View>
            )}

            {order.type == 1 && order.tradeItems.length == maxNum && maxNum > 5 && (
              <View
                className="product-more"
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({maxNum: 5});
                }}
              >
                收起商品
                <Image className="up-img" src={require('../img/jiantoudown.png')} />
              </View>
            )}

            <View className="order-bottom">
              <View>
                <View className="price">
                  <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <PriceAll
                      price={_.addZero(order.tradePrice.totalPrice)}
                      sum={order.tradeItems.concat(gifts).length}
                    />
                  </View>
                </View>

                <View style={{flexDirection: 'row'}}>
                  {endTime &&
                  order.tradeState.payState == 'NOT_PAID' &&
                  order.tradeState.flowState != 'VOID' &&
                  order.tradeState.auditState != 'NON_CHECKED' ? (
                    <View className="doajishi">
                      <Text className="count-text">支付倒计时：</Text>
                      <CountDown
                        timeStyle={{margin: 0}}
                        visibleSecond
                        visible={endTime && main.serverTime}
                        endHandle={() => {
                          let state = null;
                          //tab切换后返回需要重新选中之前的tab
                          const order_list_tab = Taro.getStorageSync('order_list_tab');
                          if (order_list_tab) {
                            state = order_list_tab.status;
                          }
                          this.props.actions.clean();
                          this.props.actions.init(state ? state : '');
                        }}
                        timeOffset={moment(endTime).diff(moment(main.serverTime), 's').toFixed(0)}
                      />
                    </View>
                  ) : null}
                </View>
              </View>

              <View style={{flexDirection: 'row'}} onClick={(e) => e.stopPropagation()}>
                {opeBtnArr.available.length > 0
                  ? opeBtnArr.available.map((availableButton, index) => {
                      if (
                        availableButton === '支付尾款' &&
                        !moment(order.tradeItems[0].tailStartTime).isSameOrBefore(main.serverTime)
                      ) {
                        const timeOffset = moment(order.tradeItems[0].tailStartTime)
                          .diff(moment(main.serverTime), 's')
                          .toFixed(0);
                        return (
                          <View key={index} className="btn-disabled">
                            <CountDown
                              timeStyle={{margin: 0, paddingTop: '2px'}}
                              allowFontScaling={false}
                              numberOfLines={1}
                              groupFlag={false}
                              prelistFlag
                              showTimeDays
                              endHandle={() => {
                                let state = null;
                                //tab切换后返回需要重新选中之前的tab
                                const order_list_tab = Taro.getStorageSync('order_list_tab');
                                if (order_list_tab) {
                                  state = order_list_tab.status;
                                }
                                this.props.actions.clean();
                                this.props.actions.init(state ? state : '');
                              }}
                              timeOffset={timeOffset}
                            />
                            <View className="buyText">后支付尾款</View>
                          </View>
                        );
                      }

                      return (
                        <View
                          key={index}
                          className={
                            availableButton == '去付款'
                              ? 'btn btn-warning'
                              : availableButton == '支付定金'
                              ? 'btn btn-warning'
                              : 'btn'
                          }
                          onClick={() => this._operationButtons(order.id, availableButton, order.payInfo.payTypeId)}
                        >
                          {availableButton}
                        </View>
                      );
                    })
                  : null}
              </View>
            </View>
          </View>
        </View>
      </View>
    );
  }
  /**
   * 订单可用操作按钮
   */
  getOpeBtnArr(order) {
    let orderButtons = {
      available: [],
      id: '',
    };

    if (order) {
      const flow = order.getIn(['tradeState', 'flowState']);
      const pay = order.getIn(['tradeState', 'payState']);

      //取消订单
      const cancelButtons = [
        ['INIT', 'NOT_PAID'],
        ['AUDIT', 'NOT_PAID'],
        ['GROUPON', 'NOT_PAID'],
      ];
      //付款
      const payButtons = [
        ['AUDIT', 'NOT_PAID'],
        ['DELIVERED_PART', 'NOT_PAID'],
        ['DELIVERED', 'NOT_PAID'],
        ['CONFIRMED', 'NOT_PAID'],
        ['GROUPON', 'NOT_PAID'],
        ['AUDIT', 'PAID_EARNEST'],
      ];
      //确认收货
      const confirmButtons = [
        ['DELIVERED', 'NOT_PAID'],
        ['DELIVERED', 'PAID'],
        ['DELIVERED', 'UNCONFIRMED'],
      ];
      //待支付定金
      const presaleDepositButtons = [['WAIT_PAY_EARNEST', 'NOT_PAID']];
      //待支付尾款
      const presaleBalanceButtons = [['WAIT_PAY_TAIL', 'PAID_EARNEST']];

      // 是否可退标识
      let canReturnFlag = order.get('canReturnFlag');
      // 是否是ipland收藏柜过来的订单
      let customerCollection = order.get("customerCollection")
      const applyReturnButtons = [
        ['AUDIT', 'PAID'],
        ['DELIVERED_PART', 'PAID'],
        ['DELIVERED', 'PAID'],
        ['COMPLETED', 'PAID'],
      ];

      if (order.getIn(['tradeState', 'flowState']) == 'GROUPON') {
        // 待成团单，不展示退货退款
        canReturnFlag = false;
      }

      let availables = [];
      if (cancelButtons.filter((button) => this._calc(button)(flow, pay)).length > 0) {
        availables.push('取消订单');
      }
      if (payButtons.filter((button) => this._calc(button)(flow, pay)).length > 0) {
        availables.push('去付款');
      }
      if (presaleDepositButtons.filter((button) => this._calc(button)(flow, pay)).length > 0) {
        availables.push('支付定金');
      }
      if (presaleBalanceButtons.filter((button) => this._calc(button)(flow, pay)).length > 0) {
        availables.push('支付尾款');
      }

      !customerCollection && canReturnFlag && applyReturnButtons.filter((button) => this._calc(button)(flow, pay)).length > 0
        ? availables.push('退货退款')
        : null;

        let confirmGoods = confirmButtons.filter((button) => this._calc(button)(flow, pay)).length > 0;
      if (confirmGoods) {
        availables.push('确认收货');
      }

      orderButtons['available'] = availables;
      orderButtons['id'] = order.get('id');
    }
    return orderButtons;
  }
  /**
   * 计算订单有效按钮
   */
  _calc = (button: Array<string>) => {
    return function (flow: string, pay: string) {
      return button[0] === flow && button[1] === pay;
    };
  };
  /**
   * 订单按钮event handler
   */
  _operationButtons = debounce(
    async (tid, button, payTypeId) => {
      console.log('button', button, payTypeId);
      let {
        order,
        actions: {goodsAction},
      } = this.props;
      //0元订单去付款直接跳转到付款成功页
      if (button == '去付款' && order.tradePrice.totalPrice == 0) {
        //直接调默认支付接口
        goodsAction.defaultPay(tid);
      }
      if (button == '去付款' && payTypeId == 0 && order.tradePrice.totalPrice != 0) {
        await Taro.navigateTo({url: `/pages/package-C/order/order-tool/order-pay/index?tid=${tid}`});
      } else if (button == '去付款' && payTypeId == 1 && order.tradePrice.totalPrice != 0) {
        Taro.navigateTo({
          url: `/pages/package-C/order/fill-payment/index?tid=${tid}`,
        });
      } else if (button == '取消订单') {
        this.props.actions.goodsAction.cancelOrder(tid);
      } else if (button == '确认收货') {
        Taro.navigateTo({
          url: `/pages/package-C/order/ship-record/index?tid=${tid}&type=${0}`,
        });
      } else if (button === '申请退款' || button === '退货退款') {
        goodsAction.applyRefund(tid);
      } else if (button == '支付定金' && payTypeId == 0 && order.tradePrice.totalPrice != 0) {
        await Taro.navigateTo({
          url: `/pages/package-C/order/order-tool/order-pay/index?tid=${tid}&isBookingSaleGoods=true`,
        });
      } else if (button == '支付尾款' && payTypeId == 0) {
        await Taro.navigateTo({url: `/pages/package-C/order/order-detail/index?id=${tid}`});
      }
    },
    500,
    {leading: true},
  );
}
